package cashpointer.mobile.dao;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import cashpointer.mobile.R;
import cashpointer.mobile.dao.DaoModel.Cashpoints;
import cashpointer.mobile.dao.DaoModel.Countries;
import cashpointer.mobile.dao.DaoModel.Owners;
import cashpointer.mobile.dao.DaoModel.Regions;

public class CashpointerProvider extends ContentProvider {
	//private static final String LOG_TAG = "OwnerProvider";
	
	// Baza danych
    private static final String DATABASE_NAME = "cashpointer.db";
    private static final int DATABASE_VERSION = 2;

    private static final UriMatcher sUriMatcher;
    
    // Tabela "owners"
    private static final String OWNERS_TABLE_NAME = "owners";
    private static HashMap<String, String> sOwnersProjectionMap;

    private static final int OWNERS = 1;
    private static final int OWNER_ID = 2;
    
    // Tabela "regions"
    private static final String REGIONS_TABLE_NAME = "regions";
    private static HashMap<String, String> sRegionsProjectionMap;

    private static final int REGIONS = 3;
    private static final int REGION_ID = 4;

    // Tabela "countries"
    private static final String COUNTRIES_TABLE_NAME = "countries";
    private static HashMap<String, String> sCountriesProjectionMap;

    private static final int COUNTRIES = 5;
    private static final int COUNTRY_ID = 6;
    
    // Tabela "cashpoints"
    private static final String CASHPOINTS_TABLE_NAME = "cashpoints";
    private static HashMap<String, String> sCashpointsProjectionMap;

    private static final int CASHPOINTS = 7;
    private static final int CASHPOINT_ID = 8;
    private static final int TOP10CASHPOINTS = 9;
    
    static {
        sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        
        // Tabela "owners"
        sUriMatcher.addURI(DaoModel.AUTHORITY, "owners", OWNERS);
        sUriMatcher.addURI(DaoModel.AUTHORITY, "owners/#", OWNER_ID);

        sOwnersProjectionMap = new HashMap<String, String>();
        sOwnersProjectionMap.put(Owners._ID, Owners._ID);
        sOwnersProjectionMap.put(Owners.NAME, Owners.NAME);
        sOwnersProjectionMap.put(Owners.SELECTED, Owners.SELECTED);
        
        // Tabela "regions"
        sUriMatcher.addURI(DaoModel.AUTHORITY, "regions", REGIONS);
        sUriMatcher.addURI(DaoModel.AUTHORITY, "regions/#", REGION_ID);

        sRegionsProjectionMap = new HashMap<String, String>();
        sRegionsProjectionMap.put(Regions._ID, Regions._ID);
        sRegionsProjectionMap.put(Regions.NAME, Regions.NAME);
        
        // Tabela "countries"
        sUriMatcher.addURI(DaoModel.AUTHORITY, "countries", COUNTRIES);
        sUriMatcher.addURI(DaoModel.AUTHORITY, "countries/#", COUNTRY_ID);

        sCountriesProjectionMap = new HashMap<String, String>();
        sCountriesProjectionMap.put(Countries._ID, Countries._ID);
        sCountriesProjectionMap.put(Countries.NAME, Countries.NAME);
        sCountriesProjectionMap.put(Countries.REGION_ID, Countries.REGION_ID);
        
        // Tabela "cashpointers"
        sUriMatcher.addURI(DaoModel.AUTHORITY, "cashpoints", CASHPOINTS);
        sUriMatcher.addURI(DaoModel.AUTHORITY, "top10cashpoints", TOP10CASHPOINTS);
        sUriMatcher.addURI(DaoModel.AUTHORITY, "cashpoints/#", CASHPOINT_ID);

        sCashpointsProjectionMap = new HashMap<String, String>();
        sCashpointsProjectionMap.put(Cashpoints._ID, Cashpoints._ID);
        sCashpointsProjectionMap.put(Cashpoints.ADDRESS_CITY, Cashpoints.ADDRESS_CITY);
        sCashpointsProjectionMap.put(Cashpoints.ADDRESS_CITY_SIMPLE, Cashpoints.ADDRESS_CITY_SIMPLE);
        sCashpointsProjectionMap.put(Cashpoints.ADDRESS_INFO, Cashpoints.ADDRESS_INFO);
        sCashpointsProjectionMap.put(Cashpoints.ADDRESS_LATITUDE, Cashpoints.ADDRESS_LATITUDE);
        sCashpointsProjectionMap.put(Cashpoints.ADDRESS_LONGITUDE, Cashpoints.ADDRESS_LONGITUDE);
        sCashpointsProjectionMap.put(Cashpoints.ADDRESS_STREET, Cashpoints.ADDRESS_STREET);
        sCashpointsProjectionMap.put(Cashpoints.ADDRESS_STREET_SIMPLE, Cashpoints.ADDRESS_STREET_SIMPLE);
        sCashpointsProjectionMap.put(Cashpoints.HASHCODE, Cashpoints.HASHCODE);
        sCashpointsProjectionMap.put(Cashpoints.OWNER_ID, Cashpoints.OWNER_ID);
        sCashpointsProjectionMap.put(Cashpoints.COUNTRY_ID, Cashpoints.COUNTRY_ID);
        sCashpointsProjectionMap.put(Cashpoints.TIME, Cashpoints.TIME);
        sCashpointsProjectionMap.put(Cashpoints.MARKED, Cashpoints.MARKED);
    }

    /**
     * Wspomaga otwieranie, tworzenie, aktualizowanie bazy danych.
     */
    private static class DatabaseHelper extends SQLiteOpenHelper {

    	private Context context;
    	
		DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            this.context = context;
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            // Tabela "owners"
        	db.execSQL("CREATE TABLE " + OWNERS_TABLE_NAME + " ("
                    + Owners._ID + " INTEGER PRIMARY KEY,"
                    + Owners.NAME + " TEXT,"
                    + Owners.SELECTED + " BOOLEAN"
                    + ");");
            
        	// Tabela "regions"
            db.execSQL("CREATE TABLE " + REGIONS_TABLE_NAME + " ("
                    + Regions._ID + " INTEGER PRIMARY KEY,"
                    + Regions.NAME + " TEXT"
                    + ");");
            
        	// Tabela "countries"
            db.execSQL("CREATE TABLE " + COUNTRIES_TABLE_NAME + " ("
                    + Countries._ID + " INTEGER PRIMARY KEY,"
                    + Countries.REGION_ID + " INTEGER,"
                    + Countries.NAME + " TEXT"
                    + ");");

        	// Tabela "cashpointers"
            db.execSQL("CREATE TABLE " + CASHPOINTS_TABLE_NAME + " ("
                    + Cashpoints._ID + " INTEGER PRIMARY KEY,"
                    + Cashpoints.ADDRESS_CITY + " TEXT,"
                    + Cashpoints.ADDRESS_CITY_SIMPLE + " TEXT,"
                    + Cashpoints.ADDRESS_INFO + " TEXT,"
                    + Cashpoints.ADDRESS_LATITUDE + " DOUBLE,"
                    + Cashpoints.ADDRESS_LONGITUDE + " DOUBLE,"
                    + Cashpoints.ADDRESS_STREET + " TEXT,"
                    + Cashpoints.ADDRESS_STREET_SIMPLE + " TEXT,"
                    + Cashpoints.HASHCODE + " TEXT,"
                    + Cashpoints.OWNER_ID + " INTEGER,"
                    + Cashpoints.COUNTRY_ID + " INTEGER,"
                    + Cashpoints.TIME + " TEXT,"
                    + Cashpoints.MARKED + " BOOLEAN"
                    + ");");
            

        	// Zaczynam tranzakcje
        	db.beginTransaction();
        	
            // Zaczytanie do bazy danych
            try {
                InputStream importSql = context.getResources().openRawResource(R.raw.import_sql_owner_region_country);
	            BufferedReader reader = new BufferedReader(new InputStreamReader(importSql));
	    		String line = null;
	    		while((line = reader.readLine()) != null) {
	    			db.execSQL(line);
	    		}

	            //Log.i(LOG_TAG, "Zaczytano: import_sql_owner_region_country");
	    		
	    		importSql = context.getResources().openRawResource(R.raw.import_sql_cashpointer_part_1);
	            reader = new BufferedReader(new InputStreamReader(importSql));
	    		line = null;
	    		while((line = reader.readLine()) != null) {
	    			db.execSQL(line);
	    		}

	            //Log.i(LOG_TAG, "Zaczytano: import_sql_cashpointer_part_1");
	    		
	    		importSql = context.getResources().openRawResource(R.raw.import_sql_cashpointer_part_2);
	            reader = new BufferedReader(new InputStreamReader(importSql));
	    		line = null;
	    		while((line = reader.readLine()) != null) {
	    			db.execSQL(line);
	    		}

	            //Log.i(LOG_TAG, "Zaczytano: import_sql_cashpointer_part_2");
	    		
	    		importSql = context.getResources().openRawResource(R.raw.import_sql_cashpointer_part_3);
	            reader = new BufferedReader(new InputStreamReader(importSql));
	    		line = null;
	    		while((line = reader.readLine()) != null) {
	    			db.execSQL(line);
	    		}

	            //Log.i(LOG_TAG, "Zaczytano: import_sql_cashpointer_part_3");
	    		// Konczenie tranzakcji powodzeniem
	    		db.setTransactionSuccessful();
	    						
            } catch (Exception e) {
            	//Log.i(LOG_TAG, "Wystapil blad podczas zaczytywania", e);
            }
            
            // Zamykanie tranzakcji
            db.endTransaction();
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            //Log.w(LOG_TAG, "Aktualizacja bazy danych z wersji: " + oldVersion + " do wersji: " + newVersion + ". Stare dane zostaly usuniete!");
            
            // Tabela "owners"
            db.execSQL("DROP TABLE IF EXISTS " + OWNERS_TABLE_NAME);

            // Tabela "regions"
            db.execSQL("DROP TABLE IF EXISTS " + REGIONS_TABLE_NAME);

            // Tabela "countries"
            db.execSQL("DROP TABLE IF EXISTS " + COUNTRIES_TABLE_NAME);

            // Tabela "cashpointers"
            db.execSQL("DROP TABLE IF EXISTS " + CASHPOINTS_TABLE_NAME);
            
            onCreate(db);
        }
    }

    // Uchwyt do bazy danych
    private DatabaseHelper mOpenHelper;

    @Override
    public boolean onCreate() {
        mOpenHelper = new DatabaseHelper(getContext());
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();		
        
        switch (sUriMatcher.match(uri)) {
	        case OWNERS: {
	            qb.setTables(OWNERS_TABLE_NAME);
	            qb.setProjectionMap(sOwnersProjectionMap);
	            break;
	        }
	        case OWNER_ID: {
	            qb.setTables(OWNERS_TABLE_NAME);
	            qb.setProjectionMap(sOwnersProjectionMap);
	            qb.appendWhere(Owners._ID + "=" + uri.getPathSegments().get(1));
	            break;
	        }
	        case REGIONS: {
	            qb.setTables(REGIONS_TABLE_NAME);
	            qb.setProjectionMap(sRegionsProjectionMap);
	            break;
	        }
	        case REGION_ID: {
	            qb.setTables(REGIONS_TABLE_NAME);
	            qb.setProjectionMap(sRegionsProjectionMap);
	            qb.appendWhere(Regions._ID + "=" + uri.getPathSegments().get(1));
	            break;
	        }
	        case COUNTRIES: {
	            qb.setTables(COUNTRIES_TABLE_NAME);
	            qb.setProjectionMap(sCountriesProjectionMap);
	            break;
	        }
	        case COUNTRY_ID: {
	            qb.setTables(COUNTRIES_TABLE_NAME);
	            qb.setProjectionMap(sCountriesProjectionMap);
	            qb.appendWhere(Countries._ID + "=" + uri.getPathSegments().get(1));
	            break;
	        }
	        case TOP10CASHPOINTS: {
	        	// Zbudowanie zapytania na bazie
	            SQLiteDatabase db = mOpenHelper.getReadableDatabase();
	            
	            String latitude = selectionArgs[0];
	            String longitude = selectionArgs[1];
	            
	            // Budowanie zapytania
	            StringBuilder sqlString = new StringBuilder();
	            sqlString.append("SELECT ");
	            sqlString.append(Cashpoints._ID);
	            sqlString.append(", ");
	            sqlString.append(Cashpoints.ADDRESS_CITY);
	            sqlString.append(", ");
	            sqlString.append(Cashpoints.ADDRESS_STREET);
	            sqlString.append(", ");
	            sqlString.append("((" + Cashpoints.ADDRESS_LATITUDE + " - " + latitude + ")*(" + Cashpoints.ADDRESS_LATITUDE + " - " + latitude + ") + (" + Cashpoints.ADDRESS_LONGITUDE + " - " + longitude + ")*(" + Cashpoints.ADDRESS_LONGITUDE + " - " + longitude + ")) AS distance");
	            sqlString.append(" FROM ");
	            sqlString.append(CASHPOINTS_TABLE_NAME);
	            sqlString.append(" WHERE ");
	            sqlString.append(selection);
	            sqlString.append(" ORDER BY distance ASC ");
	            sqlString.append(" LIMIT 10 ");
	            
	            // Logi
	            //Log.d(LOG_TAG, "Zapytanie: " + sqlString.toString());
	            
	            // Tworzenie kursora
	            Cursor cursor = db.rawQuery(sqlString.toString(), null);
	            
	            // Ustawienie URI w kursorze (do obserwacji), dzieki temu wie kiedy dane sie zmienily
	            cursor.setNotificationUri(getContext().getContentResolver(), uri);

	            return cursor;
	        }
	        case CASHPOINTS: {
	            qb.setTables(CASHPOINTS_TABLE_NAME);
	            qb.setProjectionMap(sCashpointsProjectionMap);
	            break;
	        }
	        case CASHPOINT_ID: {
	            qb.setTables(CASHPOINTS_TABLE_NAME);
	            qb.setProjectionMap(sCashpointsProjectionMap);
	            qb.appendWhere(Cashpoints._ID + "=" + uri.getPathSegments().get(1));
	            break;
	        }
	        default: {
	            throw new IllegalArgumentException("Unknown URI " + uri);
	        }
        }

        // Jesli sortowanie nie zostalo okreslone uzywane jest domysle
        String orderBy = null;
        if (TextUtils.isEmpty(sortOrder)) {
        	switch (sUriMatcher.match(uri)) {
        		case OWNER_ID:
		        case OWNERS: {
		            orderBy = Owners.DEFAULT_SORT_ORDER;
		            break;
		        }
		        case REGION_ID:
		        case REGIONS: {
		            orderBy = Regions.DEFAULT_SORT_ORDER;
		            break;
		        }
		        case COUNTRY_ID:
		        case COUNTRIES: {
		            orderBy = Countries.DEFAULT_SORT_ORDER;
		            break;
		        }
		        case CASHPOINT_ID:
		        case CASHPOINTS: {
		            orderBy = Cashpoints.DEFAULT_SORT_ORDER;
		            break;
		        }
		        default: {
		        }
	        }
        } else {
            orderBy = sortOrder;
        }

        // Zbudowanie zapytania na bazie
        SQLiteDatabase db = mOpenHelper.getReadableDatabase();
        Cursor cursor = qb.query(db, projection, selection, selectionArgs, null, null, orderBy);
        
        // Ustawienie URI w kursorze (do obserwacji), dzieki temu wie kiedy dane sie zmienily
        cursor.setNotificationUri(getContext().getContentResolver(), uri);

        return cursor;
    }

    @Override
    public String getType(Uri uri) {
        switch (sUriMatcher.match(uri)) {
	        case OWNERS: {
	            return Owners.CONTENT_TYPE;
	        }
	        case OWNER_ID: {
	            return Owners.CONTENT_ITEM_TYPE;
	        }
	        case REGIONS: {
	            return Regions.CONTENT_TYPE;
	        }
	        case REGION_ID: {
	            return Regions.CONTENT_ITEM_TYPE;
	        }
	        case COUNTRIES: {
	            return Countries.CONTENT_TYPE;
	        }
	        case COUNTRY_ID: {
	            return Countries.CONTENT_ITEM_TYPE;
	        }
	        case CASHPOINTS: {
	            return Cashpoints.CONTENT_TYPE;
	        }
	        case CASHPOINT_ID: {
	            return Cashpoints.CONTENT_ITEM_TYPE;
	        }
	        default: {
	        	throw new IllegalArgumentException("Unknown URI " + uri);
	        }
        }
    }

    @Override
    public Uri insert(Uri uri, ContentValues initialValues) {
    	ContentValues values = null;
        
        if (initialValues != null) {
            values = new ContentValues(initialValues);
        } else {
            values = new ContentValues();
        }

        // Tabela "owners"
        if (sUriMatcher.match(uri) == OWNERS) {
        	// Kolumna "name"
	        if (values.containsKey(Owners.NAME) == false) {
	        	throw new IllegalArgumentException("Kolumna name w owners nie moze byc pusta!");
	        }
	        
	        // Kolumna "selected"
	        if (values.containsKey(Owners.SELECTED) == false) {
	            values.put(Owners.SELECTED, false);	
	        }
	
	        // Otwieram baze do zapisu
	        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
	        
	        // Dodaje rekord
	        long rowId = db.insertOrThrow(OWNERS_TABLE_NAME, Owners.NAME, values);
	        if (rowId > 0) {
	            Uri noteUri = ContentUris.withAppendedId(Owners.CONTENT_URI, rowId);
	            getContext().getContentResolver().notifyChange(noteUri, null);

	            return noteUri;
	        }
        }
     
        // Tabela "regions"
        else if (sUriMatcher.match(uri) == REGIONS) {
        	// Kolumna "name"
	        if (values.containsKey(Regions.NAME) == false) {
	        	throw new IllegalArgumentException("Kolumna name w regions nie moze byc pusta!");
	        }
	        
	        // Otwieram baze do zapisu
	        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
	        
	        // Dodaje rekord
	        long rowId = db.insertOrThrow(REGIONS_TABLE_NAME, Regions.NAME, values);
	        if (rowId > 0) {
	            Uri noteUri = ContentUris.withAppendedId(Regions.CONTENT_URI, rowId);
	            getContext().getContentResolver().notifyChange(noteUri, null);

	            return noteUri;
	        }
        }

        // Tabela "countries"
        else if (sUriMatcher.match(uri) == COUNTRIES) {
        	// Kolumna "name"
	        if (values.containsKey(Countries.NAME) == false) {
	        	throw new IllegalArgumentException("Kolumna name w countries nie moze byc pusta!");
	        }
	        
	        // Kolumna "regionId"
	        if (values.containsKey(Countries.REGION_ID) == false) {
	        	throw new IllegalArgumentException("Kolumna regionId w countries nie moze byc pusta!");
	        }
	        
	        // Otwieram baze do zapisu
	        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
	        
	        // Dodaje rekord
	        long rowId = db.insertOrThrow(COUNTRIES_TABLE_NAME, Countries.NAME, values);
	        if (rowId > 0) {
	            Uri noteUri = ContentUris.withAppendedId(Countries.CONTENT_URI, rowId);
	            getContext().getContentResolver().notifyChange(noteUri, null);

	            return noteUri;
	        }
        }
        
        // Tabela "cashpointers"
        else if (sUriMatcher.match(uri) == CASHPOINTS) {
        	// Kolumna "addressCity"
	        if (values.containsKey(Cashpoints.ADDRESS_CITY) == false) {
	        	throw new IllegalArgumentException("Kolumna addressCity w cashpointers nie moze byc pusta!");
	        }
	        
	        // Kolumna "addressCitySimple"
	        if (values.containsKey(Cashpoints.ADDRESS_CITY_SIMPLE) == false) {
	        	throw new IllegalArgumentException("Kolumna addressCitySimple w cashpointers nie moze byc pusta!");
	        }

	        // Kolumna "addressInfo"
	        if (values.containsKey(Cashpoints.ADDRESS_INFO) == false) {
	        	values.put(Cashpoints.ADDRESS_INFO, "");
	        }
	        
	        // Kolumna "addressLatitude"
	        if (values.containsKey(Cashpoints.ADDRESS_LATITUDE) == false) {
	        	throw new IllegalArgumentException("Kolumna addressLatitude w cashpointers nie moze byc pusta!");
	        }
	        
	        // Kolumna "addressLongitude"
	        if (values.containsKey(Cashpoints.ADDRESS_LONGITUDE) == false) {
	        	throw new IllegalArgumentException("Kolumna addressLatitude w cashpointers nie moze byc pusta!");
	        }
	        
	        // Kolumna "addressStreet"
	        if (values.containsKey(Cashpoints.ADDRESS_STREET) == false) {
	        	throw new IllegalArgumentException("Kolumna addressStreet w cashpointers nie moze byc pusta!");
	        }
	        
	        // Kolumna "addressStreetSimple"
	        if (values.containsKey(Cashpoints.ADDRESS_STREET_SIMPLE) == false) {
	        	throw new IllegalArgumentException("Kolumna addressStreetSimple w cashpointers nie moze byc pusta!");
	        }

	        // Kolumna "hashcode"
	        if (values.containsKey(Cashpoints.HASHCODE) == false) {
	        	throw new IllegalArgumentException("Kolumna hashcode w cashpointers nie moze byc pusta!");
	        }

	        // Kolumna "ownerId"
	        if (values.containsKey(Cashpoints.OWNER_ID) == false) {
	        	throw new IllegalArgumentException("Kolumna ownerId w cashpointers nie moze byc pusta!");
	        }

	        // Kolumna "countryId"
	        if (values.containsKey(Cashpoints.COUNTRY_ID) == false) {
	        	throw new IllegalArgumentException("Kolumna countryId w cashpointers nie moze byc pusta!");
	        }

	        // Kolumna "time"
	        if (values.containsKey(Cashpoints.TIME) == false) {
	        	values.put(Cashpoints.TIME, "");
	        }

	        // Kolumna "time"
	        if (values.containsKey(Cashpoints.MARKED) == false) {
	        	values.put(Cashpoints.MARKED, false);
	        }
	        
	        // Otwieram baze do zapisu
	        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
	        
	        // Dodaje rekord
	        long rowId = db.insertOrThrow(CASHPOINTS_TABLE_NAME, Cashpoints.ADDRESS_CITY, values);
	        if (rowId > 0) {
	            Uri cashpointerUri = ContentUris.withAppendedId(Cashpoints.CONTENT_URI, rowId);
	            getContext().getContentResolver().notifyChange(cashpointerUri, null);

	            return cashpointerUri;
	        }
        }
        
        throw new SQLException("Blad podczas dodawania rekordu " + uri);
    }

    @Override
    public int delete(Uri uri, String where, String[] whereArgs) {
    	// Otwieram baze do zapisu
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        
        int count;
        switch (sUriMatcher.match(uri)) {
	        case OWNERS: {
	            count = db.delete(OWNERS_TABLE_NAME, where, whereArgs);
	            break;
	        }
	        case OWNER_ID: {
	            String id = uri.getPathSegments().get(1);
	            count = db.delete(OWNERS_TABLE_NAME, Owners._ID + "=" + id
	                    + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
	            break;
	        }
	        case REGIONS: {
	            count = db.delete(REGIONS_TABLE_NAME, where, whereArgs);
	            break;
	        }
	        case REGION_ID: {
	            String id = uri.getPathSegments().get(1);
	            count = db.delete(REGIONS_TABLE_NAME, Regions._ID + "=" + id
	                    + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
	            break;
	        }
	        case COUNTRIES: {
	            count = db.delete(COUNTRIES_TABLE_NAME, where, whereArgs);
	            break;
	        }
	        case COUNTRY_ID: {
	            String id = uri.getPathSegments().get(1);
	            count = db.delete(COUNTRIES_TABLE_NAME, Countries._ID + "=" + id
	                    + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
	            break;
	        }
	        case CASHPOINTS: {
	            count = db.delete(CASHPOINTS_TABLE_NAME, where, whereArgs);
	            break;
	        }
	        case CASHPOINT_ID: {
	            String id = uri.getPathSegments().get(1);
	            count = db.delete(CASHPOINTS_TABLE_NAME, Cashpoints._ID + "=" + id
	                    + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
	            break;
	        }
	        default: {
	            throw new IllegalArgumentException("Unknown URI " + uri);
	        }
        }

        getContext().getContentResolver().notifyChange(uri, null);

        return count;
    }

    @Override
    public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
    	// Otwieram baze do zapisu
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        
        int count;
        switch (sUriMatcher.match(uri)) {
	        case OWNERS: {
	            count = db.update(OWNERS_TABLE_NAME, values, where, whereArgs);
	            break;
	        }
	        case OWNER_ID: {
	            String id = uri.getPathSegments().get(1);
	            count = db.update(OWNERS_TABLE_NAME, values, Owners._ID + "=" + id
	                    + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
	            break;
	        }
	        case REGIONS: {
	            count = db.update(REGIONS_TABLE_NAME, values, where, whereArgs);
	            break;
	        }
	        case REGION_ID: {
	            String id = uri.getPathSegments().get(1);
	            count = db.update(REGIONS_TABLE_NAME, values, Regions._ID + "=" + id
	                    + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
	            break;
	        }
	        case COUNTRIES: {
	            count = db.update(COUNTRIES_TABLE_NAME, values, where, whereArgs);
	            break;
	        }
	        case COUNTRY_ID: {
	            String id = uri.getPathSegments().get(1);
	            count = db.update(COUNTRIES_TABLE_NAME, values, Countries._ID + "=" + id
	                    + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
	            break;
	        }
	        case CASHPOINTS: {
	            count = db.update(CASHPOINTS_TABLE_NAME, values, where, whereArgs);
	            break;
	        }
	        case CASHPOINT_ID: {
	            String id = uri.getPathSegments().get(1);
	            count = db.update(CASHPOINTS_TABLE_NAME, values, Cashpoints._ID + "=" + id
	                    + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
	            break;
	        }
	        default: {
	            throw new IllegalArgumentException("Unknown URI " + uri);
	        }
        }
        
        getContext().getContentResolver().notifyChange(uri, null);
        
        return count;
    }
}
